'use strict';

module.exports = {
  success(result = null, msg = 'SUCCESS') {
    return {
      code: '0',
      msg,
      result,
    };
  },
  fail(msg = 'FAIL', result = null) {
    return {
      code: '-1',
      msg,
      result,
    };
  },
  stringRule(len) {
    return {
      type: 'string',
      required: true,
      trim: true,
      max: len,
    };
  },
  pageString() {
    return {
      type: 'string',
      required: true,
      trim: true,
      format: /^\+?[1-9]\d*$/,
    };
  },
  paramError(e) {
    const errorFirst = e.errors[0];
    const errorMessage = '参数 ' + errorFirst.field + ' 异常';
    return this.fail(errorMessage, e.errors[0]);
  },
  arrayToTree(data, pid, emptyChildren = true) {
    const res = [];
    data.forEach(item => {
      if (item.parentId === pid) {
        const itemChildren = this.arrayToTree(data, item.id, emptyChildren);
        if (itemChildren.length) {
          item.children = itemChildren;
        }
        // else {
        //   if (emptyChildren) {
        //     item.children = [];
        //   }
        // }
        res.push(item);
      }
    });
    return res;
  },
};
